package ch.headshot.photomap.client.gpx.impl;

import java.util.ArrayList;
import java.util.List;

import ch.headshot.photomap.client.gpx.Track;
import ch.headshot.photomap.client.gpx.TrackSegment;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;

public class TrackImpl implements Track {

	private static final String TRKSEG = "trkseg";
	private static final String NAME = "name";
	private final Element item;
	private ArrayList<TrackSegment> segments;

	public TrackImpl(Element item) {
		this.item = item;
	}

	@Override
	public String toString() {
		StringBuffer b = new StringBuffer("<trk>");
		if (getName() != null) {
			b.append("<name>");
			b.append(getName());
			b.append("</name>");
		}
		for (TrackSegment seg : getSegments()) {
			b.append(seg);
		}
		b.append("</trk>");
		return b.toString();
	}

	public List<TrackSegment> getSegments() {
		if (segments == null) {
			segments = new ArrayList<TrackSegment>();
			NodeList rtes = item.getElementsByTagName(TRKSEG);
			for (int i = 0; i < rtes.getLength(); i++) {
				segments.add(new TrackSegmentImpl((Element) rtes.item(i)));
			}
		}

		return segments;
	}

	public String getName() {
		NodeList names = item.getElementsByTagName(NAME);
		assert names.getLength() < 2;
		if (names.getLength() > 0) {
			NodeList childNodes = names.item(0).getChildNodes();
			if (childNodes.getLength() > 0) {
				return childNodes.item(0).getNodeValue();
			}
		}
		return null;
	}
}
